package com.mqz.seckill.interceptor;
//自定义拦截器

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mqz.seckill.config.RequestLimit;
import com.mqz.seckill.config.UserContext;
import com.mqz.seckill.pojo.User;
import com.mqz.seckill.service.UserService;
import com.mqz.seckill.util.CookieUtil;
import com.mqz.seckill.vo.RespBean;
import com.mqz.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class RequestLimitInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        User user = this.getUser(request, response);
        UserContext.setUser(user);

        HandlerMethod method = (HandlerMethod) handler;
        RequestLimit requestLimit = method.getMethodAnnotation(RequestLimit.class);

        if (requestLimit == null) {//未加requestLimit注解
            return true;
        }

        //        String uri = request.getRequestURI();
//
//        ValueOperations ops = redisTemplate.opsForValue();
//        Integer requestCount = (Integer) ops.get(uri + ":" + user.getId());
//        String key = uri + ":" + user.getId();
//
//        if (requestCount == null) {
//            ops.set(key, 1, 5, TimeUnit.SECONDS);
//        } else if (requestCount < 5) {
//            ops.increment(key);
//        } else {
//            return RespBean.error(RespBeanEnum.OVER_REQUEST_ERROR);
//        }
        //验证用户登录
        if (requestLimit.requireLogin()) {
            if (user == null) {
                this.render(response, RespBean.error(RespBeanEnum.SESSION_ERROR));
                return false;
            }
        }

        //验证用户防刷
        String uri = request.getRequestURI();
        ValueOperations ops = redisTemplate.opsForValue();
        Integer requestCount = (Integer) ops.get(uri + ":" + user.getId());
        String key = uri + ":" + user.getId();

        if (requestCount == null) {
            ops.set(key, 1, requestLimit.timeout(), TimeUnit.SECONDS);
        } else if (requestCount < requestLimit.maxCount()) {
            ops.increment(key);
        } else {
            this.render(response, RespBean.error(RespBeanEnum.OVER_REQUEST_ERROR));
            return false;
        }

        return true;
    }

    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        if (!StringUtils.hasText(userTicket)) {
            return null;
        } else {
            return userService.getUserByCookie(userTicket, request, response);
        }
    }

    private void render(HttpServletResponse response, RespBean respBean) throws IOException {
        response.setContentType("app;ocation/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();

//        writer.write(new ObjectMapper().writeValueAsString(respBean));
        String s = JSONUtil.toJsonPrettyStr(respBean);

        writer.write(s);
        writer.flush();
        writer.close();
    }
}
